<template>
  <div class='container'>
    <el-form :rules="rules" ref="addForm" :model="form" label-width="80px">
        <el-form-item prop="subjectName"  label="学科名称" style="width: 100%;">
          <el-input v-model="form.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="form.isFrontDisplay"
            />
        </el-form-item>
        <el-form-item>
          <!-- <el-button @click="$emit('close')">取消</el-button> -->
          <el-button @click="hClosed">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
       </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    row: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      form: {
        subjectName: '', // 学科名称
        username: '', // 创建者
        addDate: '', // 创建日期
        isFrontDisplay: false, // 前台是否显示
        twoLevelDirectory: '', // 二级目录
        tags: '', // 标签
        totals: '' // 题目数量
      },
      rules: {
        subjectName: [
          { required: true, message: '输入内容不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  created () {
    // console.log(this.row)
    this.EditSubjects()
  },
  methods: {
    async hSubmit () {
      try {
        //   兜底校验
        const valid = await this.$refs.addForm.validate().catch(e => e)
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      } catch (e) {
        console.log(e)
      }
    },
    // 编辑学科
    async  doEdit () {
      try {
        await update({
          id: this.row.id,
          isFrontDisplay: this.form.isFrontDisplay,
          subjectName: this.form.subjectName
        })
        // console.log(res)
        this.$message.success('修改成功')
        this.$emit('success')
      } catch (e) {
        console.log(e)
      }
    },
    // 添加学科
    async doAdd () {
      try {
        await add(this.form)
        // console.log(res)
        this.$message.success('添加成功')
        this.$emit('success')
      } catch (e) {
        console.log(e)
      }
    },
    async EditSubjects () {
      // console.log(this.row.isFrontDisplay)
      // this.form.isFrontDisplay = Boolean(this.row.isFrontDisplay)
      this.form = { ...this.row, isFrontDisplay: Boolean(this.row.isFrontDisplay) }
    },
    hClosed () {
      this.$emit('close')
    },
    resetForm () {
      // 清空表单数据
      this.form = {
        subjectName: '', // 学科名称
        username: '', // 创建者
        addDate: '', // 创建日期
        isFrontDisplay: false, // 前台是否显示
        twoLevelDirectory: '', // 二级目录
        tags: '', // 标签
        totals: '' // 题目数量
      }
      // 清空校验结果
      this.$refs.addForm.resetFields()
    }
  }
}
</script>

<style scoped lang='less'></style>
